package com.atguigu.tingshu.user.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.common.config.redis.RedisConfig;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.album.TrackStatVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitService rabbitService;

    /**
     * 获取声音上次跳出时间
     *
     * @param trackId 音频ID
     * @return
     */
    @Override
    public BigDecimal getTrackBreakSecond(Long userId, Long trackId) {
        //1.根据用户ID确定操作集合名称 形式为：固定前缀_用户ID=userListenProcess_userId
        String collctionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        UserListenProcess userListenProcess = mongoTemplate.findOne(
                new Query().addCriteria(Criteria.where("userId").is(userId).and("trackId").is(trackId)),
                UserListenProcess.class, collctionName);
        if (userListenProcess != null) {
            return userListenProcess.getBreakSecond();
        }
        return BigDecimal.valueOf(0);
    }

    /**
     * 更新声音播放进度
     *
     * @param userListenProcessVo
     */
    @Override
    public void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo) {
        //跳出时间格式化
        userListenProcessVo.setBreakSecond(userListenProcessVo.getBreakSecond().setScale(0, RoundingMode.DOWN));
        //getMongoDB集合名称
        String collctionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        UserListenProcess userListenProcess = mongoTemplate.findOne(
                new Query().addCriteria(Criteria.where("userId").is(userId).and("trackId").is(userListenProcessVo.getTrackId())),
                UserListenProcess.class, collctionName);
        if (userListenProcess == null) {
            userListenProcess = new UserListenProcess();
            userListenProcess.setUserId(userId);
            userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
            userListenProcess.setTrackId(userListenProcessVo.getTrackId());
            userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            userListenProcess.setCreateTime(new Date());
            userListenProcess.setUpdateTime(new Date());
        } else {
            userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            userListenProcess.setUpdateTime(new Date());
        }
        mongoTemplate.save(userListenProcess, collctionName);

        //TODO 基于MQ可靠性消息，更新声音/专辑(播放量)在MySQL以及ES中统计数值
        //当天内判断当前用户是否为第一次收听更新统计数值 核心：生产者生产消息幂等性
        //关键点找出业务标识作为RedisKey：前缀:用户ID_专辑ID_声音ID
        String redisKey = RedisConstant.USER_TRACK_REPEAT_STAT_PREFIX + userId + "_" + userListenProcessVo.getAlbumId() + "_" + userListenProcessVo.getTrackId();
        Long ttl = DateUtil.endOfDay(new Date()).getTime() - new Date().getTime();
        Boolean saved = redisTemplate.opsForValue().setIfAbsent(redisKey, "1", ttl, TimeUnit.MILLISECONDS);

        if (saved) {
        //缓存成功,发送MQ消息保存至MySQL
            TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
            trackStatMqVo.setBusinessNo(IdUtil.fastUUID());
            trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
            trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
            trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
            trackStatMqVo.setCount(1);
            rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE,trackStatMqVo);
        }

    }

    /**
     * 获取当前用户最近播放声音
     */
    @Override
    public Map<String, Long> getLatelyTrack(Long userId) {
        String collectName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        UserListenProcess userListenProcess = mongoTemplate.findOne(
                new Query().addCriteria(Criteria.where("userId").is(userId)).with(PageRequest.of(0, 1, Sort.Direction.DESC, "updateTime")),
                UserListenProcess.class, collectName);
        if (userListenProcess != null) {
            HashMap<String, Long> trackInfoMap = new HashMap<String, Long>();
            trackInfoMap.put("albumId", userListenProcess.getAlbumId());
            trackInfoMap.put("trackId", userListenProcess.getTrackId());
            return trackInfoMap;
        }
        return null;
    }
}
